package android.slc.box.core.ui;

import android.slc.box.core.notification.NotificationObserver;
import android.slc.box.core.notification.SaxSysNotificationObserver;
import android.slc.box.core.scope.IntentScope;
import android.slc.box.rxlifecycle.SimpleLifecycleScopeProvider;
import autodispose2.AutoDispose;
import autodispose2.AutoDisposeConverter;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import de.saxsys.mvvmfx.InjectScope;
import de.saxsys.mvvmfx.SceneLifecycle;

import java.util.ArrayList;
import java.util.List;

/**
 * 此处需要拿到窗口关闭事件监听，然后通过RxJava生命周期绑定来解除该节目的操作
 * 系统的事件通知中心造成内存泄漏，所有实现Scope的事件都将会受到影响，此类重写相关事件方法来实现时事件通知
 * @author slc
 * @date 2022/03/21 下午 1:42
 */
public class BaseViewModel extends ProtectedViewModelImpl implements SceneLifecycle {
    protected final static Log LOG = LogFactory.get();
    public final static String EVENT_ON_VIEW_ADDED = "onViewAdded";
    public final static String EVENT_ON_VIEW_REMOVED = "onViewRemoved";
    public final static String EVENT_ON_VIEW_DESTROY = "onViewDestroy";
    public final static String EVENT_FINISH_WINDOW = "finishWindow";
    public final static String EVENT_FINISH_VIEW = "finishView";

    /**
     * 直男的方式来销毁界面
     * 当监听到remove时，调用销毁
     */
    private boolean straightManDestroyType = true;
    /**
     * 是否清除
     */
    private volatile boolean cleared = false;

    /**
     * intent空间
     */
    @InjectScope
    private IntentScope intentScope;

    /**
     * 生命周期代理
     */
    protected SimpleLifecycleScopeProvider lifecycleScopeProvider;

    /**
     * vmBox列表
     */
    protected final List<VmBox> vmBoxList = new ArrayList<>();

    protected final NotificationObserver loadIntentScopeNotification = new NotificationObserver() {
        @Override
        public void receivedNotification(String key, Object... payload) {
            onIntentScopeNotification(key, payload);
        }

    };

    /**
     * 初始化，由框架自动调用
     */
    public final void initialize() {
        //创建RxJava
        this.lifecycleScopeProvider = SimpleLifecycleScopeProvider.createStart();
        this.straightManDestroyType = this.setStraightManDestroyType();
        //
        LOG.info("ViewModel.initialize");
    }

    public boolean setStraightManDestroyType() {
        return straightManDestroyType;
    }

    public final boolean isStraightManDestroyType() {
        return straightManDestroyType;
    }

    public IntentScope getIntentScope() {
        return this.intentScope;
    }

    private void onIntentScopeNotification(String key, Object... payload) {
        if (IntentScope.EVENT_VIEW_RESULT.equals(key)) {
            onIntentResultView(SaxSysNotificationObserver.getResultByView(payload));
        } else if (IntentScope.EVENT_LIST_REFRESH.equals(key)) {
            onIntentRefreshList(SaxSysNotificationObserver.getResultByView(payload));
        } else {
            onIntentEvent(key, payload);
        }
    }

    protected void onIntentResultView(Object payload) {

    }

    protected void onIntentRefreshList(Object payload) {

    }

    protected void onIntentEvent(String key, Object... payload) {

    }

    /**
     * 绑定生命周期
     *
     * @param <T>
     * @return
     */
    public <T> AutoDisposeConverter<T> bindToLifecycle() {
        return AutoDispose.autoDisposable(lifecycleScopeProvider);
    }

    @Override
    public final void onViewAdded() {
        LOG.info("ViewModel.onViewAdded");
        publish(EVENT_ON_VIEW_ADDED);
    }

    /**
     * 执行了remove，就必定是切换了该视图
     * 没有执行remove但执行了销毁事件就必定是直接关闭了窗口
     */
    @Override
    public final void onViewRemoved() {
        onViewRemoved(true);
    }

    /**
     * 来自系统
     * 不推荐调用
     * @param fromFrame
     */
    @Deprecated
    protected final void onViewRemoved(boolean fromFrame) {
        try {
            LOG.info("ViewModel.onViewRemoved");
            publish(EVENT_ON_VIEW_REMOVED);
            if (isStraightManDestroyType() || !fromFrame) {
                publish(EVENT_ON_VIEW_DESTROY);
            }
        } catch (Exception e) {
            Log.get().info("");
        }
    }

    protected void registerVmBox(VmBox vmBox) {
        if (vmBox != null && !vmBoxList.contains(vmBox)) {
            vmBox.setRxLifecycleScopeProvider(this.lifecycleScopeProvider);
            vmBox.registerLiveEventFromVm(this);
            vmBoxList.add(vmBox);
        }
    }

    protected void unRegisterVmBox(VmBox vmBox) {
        vmBoxList.remove(vmBox);
        vmBox.clear();
    }

    /**
     * 此处暂时为私有
     */
    protected void onCleared() {
        this.intentScope = null;
        //销毁vmBox
        for (VmBox vmBox : this.vmBoxList) {
            if (vmBox != null) {
                vmBox.clear();
            }
        }
        this.vmBoxList.clear();
        //销毁生命周期空间
        this.lifecycleScopeProvider.stop();

        LOG.info("ViewModel.onCleared");
    }

    protected final boolean isCleared() {
        return this.cleared;
    }

    final void clear() {
        this.cleared = true;
        onCleared();
    }

    /**
     * 关闭窗口
     */
    protected void finish() {
        publish(EVENT_FINISH_WINDOW);
    }

    /**
     * 关闭视图
     */
    protected void finishView() {
        publish(EVENT_FINISH_VIEW);
    }

}
